import React, { useEffect, useRef, useState } from 'react';
import { Checkbox, Input, Table } from 'antd';
import styles from './index.less';
import TimeQuanTum from './TimeQuanTum';
import { tableLocale } from '@/tool/components/PageEmpty';
import { initTimeEnum, POWER_ENUM } from '../../helper';

const TIME_ENUM = initTimeEnum();

export const AddTable = ({ tableData = {}, setTableData, loading }) => {
  const [checkedAll, setCheckedAll] = useState({
    quantityChecked: false,
    priceChecked: false,
  });

  const inputData = useRef({});

  useEffect(() => {
    initTimeEnum();
  }, []);

  useEffect(() => {
    const isNoData = tableData.allDataIds.length !== 0;
    setCheckedAll({
      quantityChecked:
        isNoData &&
        tableData.allDataIds.sort().toString() === tableData.quantityCheckedIds.sort().toString(),
      priceChecked:
        isNoData &&
        tableData.allDataIds.sort().toString() === tableData.priceCheckedIds.sort().toString(),
    });
  }, [tableData.allDataIds]);

  const selectAll = (e, key) => {
    const checked = e.target.checked;
    const obj = tableData.dataSourceObj;
    for (let k in obj) {
      obj[k] = { ...obj[k], [key]: checked };
    }
    const ids = checked ? tableData.allDataIds : [];
    setCheckedAll({ ...checkedAll, [key]: checked });
    setTableData({ dataSourceObj: obj, [key + 'Ids']: ids });
  };

  const changeChecked = (e, id, key) => {
    const obj = tableData.dataSourceObj;
    const checked = e.target.checked;
    obj[id] = { ...obj[id], [key]: checked };
    let ids = tableData[key + 'Ids'];
    ids = checked ? [...ids, id] : ids.filter((i) => i !== id);
    setTableData({ dataSourceObj: obj, [key + 'Ids']: ids });
  };

  const deleteRows = (id) => {
    const obj = tableData.dataSourceObj;
    delete obj[id];
    const quantityCheckedIds = tableData.quantityCheckedIds.filter((i) => i !== id);
    const priceCheckedIds = tableData.priceCheckedIds.filter((i) => i !== id);
    setTableData({
      quantityCheckedIds,
      priceCheckedIds,
      dataSourceObj: obj,
    });
  };

  const changeLineValue = (e, id, key) => {
    let value = e.target.value;
    inputData.current = { value, key, id };
    const obj = tableData.dataSourceObj;
    obj[id][key] = value;
    setTableData({ dataSourceObj: obj });
  };

  const inputBlur = () => {
    const obj = tableData.dataSourceObj;
    let { value, id, key } = inputData.current;
    value = isNaN(Number(value)) ? 0 : Number(value);
    obj[id][key] = value.toFixed(key === POWER_ENUM.POWER_COUNT ? 3 : 1);
    setTableData({ dataSourceObj: obj });
  };

  const changeResultFn = (selectArr, item) => {
    const obj = tableData.dataSourceObj;
    obj[item.id] = { ...obj[item.id], startTime: selectArr[0], endTime: selectArr[1] };
    setTableData({ dataSourceObj: obj });
    clickFn(item.id, undefined);
  };

  const clickFn = (id, e) => {
    e && e.stopPropagation();
    const obj = tableData.dataSourceObj;
    obj[id] = { ...obj[id], showTimePicker: !obj[id].showTimePicker };
    setTableData({ dataSourceObj: obj });
  };

  const columns = [
    {
      dataIndex: 'index',
      title: '序号',
      width: '70px',
    },
    {
      dataIndex: 'startTime',
      title: '时间段',
      width: '110px',
      render: (v, record) => (
        <TimeQuanTum
          visable={record.showTimePicker}
          dataSource={tableData.dataSource}
          presentData={record}
          changeResultFn={changeResultFn}
        >
          <span className={styles.timeCol} onClick={(e) => clickFn(record.id, e)}>
            {`${TIME_ENUM[record?.startTime] || ''}-${TIME_ENUM[record?.endTime] || ''}`}
          </span>
        </TimeQuanTum>
      ),
    },
    {
      dataIndex: POWER_ENUM.POWER_COUNT,
      title: (
        <div>
          <Checkbox
            style={{ marginRight: 5 }}
            checked={checkedAll.quantityChecked}
            onChange={(e) => selectAll(e, 'quantityChecked')}
            indeterminate={
              tableData.quantityCheckedIds.length > 0 &&
              tableData.quantityCheckedIds.length < tableData.allDataIds.length
            }
          />
          电量(MWh)
        </div>
      ),
      width: '130px',
      render: (v, record) => (
        <div className={styles.tableLine}>
          <Checkbox
            style={{ marginRight: 5 }}
            onChange={(e) => changeChecked(e, record.id, 'quantityChecked')}
            checked={!!record.quantityChecked}
          />
          <Input
            className={styles.tableLineInput}
            value={v}
            onChange={(e) => changeLineValue(e, record.id, POWER_ENUM.POWER_COUNT)}
            onBlur={inputBlur}
          />
        </div>
      ),
    },
    {
      dataIndex: POWER_ENUM.POWER_PRICE,
      title: (
        <div>
          <Checkbox
            style={{ marginRight: 5 }}
            checked={checkedAll.priceChecked}
            onChange={(e) => selectAll(e, 'priceChecked')}
            indeterminate={
              tableData.priceCheckedIds.length > 0 &&
              tableData.priceCheckedIds.length < tableData.allDataIds.length
            }
          />
          电价(元/MWh)
        </div>
      ),
      width: '130px',
      render: (v, record) => (
        <div className={styles.tableLine}>
          <Checkbox
            style={{ marginRight: 5 }}
            onChange={(e) => changeChecked(e, record.id, 'priceChecked')}
            checked={!!record.priceChecked}
          />
          <Input
            className={styles.tableLineInput}
            value={v}
            onChange={(e) => changeLineValue(e, record.id, POWER_ENUM.POWER_PRICE)}
            onBlur={inputBlur}
          />
        </div>
      ),
    },
    {
      dataIndex: 'key',
      title: '操作',
      width: '60px',
      render: (v, record) => (
        <span className={styles.delete} onClick={() => deleteRows(record.id)}>
          删除
        </span>
      ),
    },
  ];

  return (
    <Table
      className={styles.table}
      size={'small'}
      loading={loading}
      locale={tableLocale}
      scroll={{
        y: 270,
        height: 270,
      }}
      pagination={false}
      columns={columns}
      rowKey={'id'}
      dataSource={tableData.dataSource || []}
    />
  );
};
